jfblog

Random logs and notes

Convert between matrices and arrays

Converting between arrays and matrices

When using numpy, it is sometimes useful to do part of calculations using matrices rather than arrays. Thus it is interesting to be able to convert between the two types. This is easily done as follows, where we use the * operator in functions definitions. This enables to pass a variable number of parameters (in a form of an implicit lists, which is unpacked implicitely then after).

In [1]:
def tomat(*Z):
    """Converts the list of arrays in *Z to matrices"""
    Out=[]
    for iter in Z:
        iter=mat(iter)
        Out.append(iter)
    return Out
    
def toarray(*Z):
    """Converts the list of matrices in *Z to arrays"""
    Out=[]
    for iter in Z:
        iter=array(iter)
        Out.append(iter)
    return Out  

A test:

In [2]:
    A=randn(10,10)
    B=randn(7,14)
    C=[1, 3, 4]
    D,E,F=tomat(A,B,C)
    print(type(D))
    G,H,L=toarray(D,E,F)
    print(type(L))
    #
    A,B,C=tomat(A,B,C)
    print(type(A))
<class 'numpy.matrixlib.defmatrix.matrix'>
<class 'numpy.ndarray'>
<class 'numpy.matrixlib.defmatrix.matrix'>

A possible use is for situations like this: given two colomns vectors \(x\) and \(y\) and a matrix \(A\), compute \[z=x^T A y\]

In [11]:
x=randn(10)
y=randn(10)
A=randn(10,10)
# These are all arrays
print("Type of x: ",type(x))
# The expression computed using array's dot products:
z=x.dot(A).dot(y)
print(z)
# And computed using classical matrix notations
x,y,A=tomat(x,y,A)
print("Shape of x: ",shape(x))
zz=x*A*y.T
print(zz)
Type of x:  <class 'numpy.ndarray'>
19.6823406445
(1, 10)
[[ 19.68234064]]

A script file 'tofromatarray.py' is available here

In [1]:
HTML(the_end(theNotebook))
Out[1]:

This post was written as an IPython notebook. It is available for download or as a static html.

Creative Commons License
jfblog by J.-F. Bercher is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.
Based on a work at http://jfbercher.github.io/.

misc

Comments